package com.easyUploader.controller;

import com.common.result.ResponseResultAdvice;
import com.easyUploader.entity.vo.FileChunkVo;
import com.easyUploader.entity.dto.FileUpLoadResultDto;
import com.easyUploader.property.LocalFileProperty;
import com.easyUploader.service.IBucketService;
import com.easyUploader.service.IFileChunkService;
import com.easyUploader.service.IFileService;
import com.easyUploader.service.IFileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author 大忽悠
 * @create 2022/9/15 11:09
 */
@Validated
@RestController
@RequestMapping("/uploader")
@RequiredArgsConstructor
@ResponseResultAdvice
@Slf4j
@Api(tags = "文件请求")
public class FileUploadController {
    private final IFileService fileService;
    private final IFileChunkService fileChunkService;
    private final IFileStorageService fileStorageService;
    private final IBucketService iBucketService;
    private final LocalFileProperty localFileProperty;

    @ApiOperation("秒传检测")
    @GetMapping("/checkFileUpload")
    public FileUpLoadResultDto checkFileUpload(@RequestParam("fileMd5")String fileMd5) {
        return fileStorageService.checkFileUpLoad(fileMd5,fileChunkService,localFileProperty);
    }

    @ApiOperation("分片上传")
    @ApiResponse(message = "返回文件访问url",code = 200)
    @PostMapping("/chunkUpload")
    public String chunkUpload(FileChunkVo fileChunkVo) {
        String visitUrl = fileService.uploadFile(fileChunkVo);
        log.info("当前分片访问的URL为: {}",visitUrl);
        return visitUrl;
    }

    @ApiOperation("根据桶和文件名或者目录名下载文件")
    @GetMapping( "/download/bucket")
    public void downLoadByBucketAndFileName(HttpServletRequest request, HttpServletResponse response, @RequestParam("bucket") String bucket, @RequestParam("path")@ApiParam("fileKey/filename") String path) throws IOException {
        fileStorageService.downLoadByBucketAndFileName(bucket,path,localFileProperty,iBucketService, request, response);
    }

    @ApiOperation("根据桶和文件名删除文件")
    @GetMapping( "/delete")
    public Boolean deleteByBucketAndFileName(HttpServletRequest request, HttpServletResponse response, @RequestParam("bucket") String bucket, @RequestParam("name") String name) throws IOException {
        return fileStorageService.deleteByBucketAndFileName(bucket,name,iBucketService,localFileProperty, request, response);
    }
}
